package com.newworld.dmsapp2.activity.designtask;

import java.io.File;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.newworld.dmsapp2.BaseActivity;
import com.newworld.dmsapp2.R;
import com.newworld.dmsapp2.activity.MainActivity;
import com.newworld.dmsapp2.activity.ServiceScheduleAccomplishActivity;
import com.newworld.dmsapp2.activity.ServiceScheduleActivity;
import com.newworld.dmsapp2.activity.SettingSoftwareVersionActivity;
import com.newworld.dmsapp2.activity.ToDoTaskListActivity;
import com.newworld.dmsapp2.activity.UploadService;
import com.newworld.dmsapp2.activity.serviceapply.ViewPagerActivity;
import com.newworld.dmsapp2.bean.AreaType;
import com.newworld.dmsapp2.bean.Server;
import com.newworld.dmsapp2.bean.Task;
import com.newworld.dmsapp2.bean.User;
import com.newworld.dmsapp2.ui.view.CustomDialog;
import com.newworld.dmsapp2.ui.view.CustomLoadingDialog;
import com.newworld.dmsapp2.util.Config;
import com.newworld.dmsapp2.util.HttpUtil;
import com.newworld.dmsapp2.util.SingleSample;
import com.newworld.dmsapp2.util.SysApplication;
import com.newworld.dmsapp2.util.Tool;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

/**
 * 
 * @author long 派单和改派的界面
 */
public class AssignAndReassignTaskActivity extends BaseActivity implements
		OnClickListener {
	private RelativeLayout selectServerRv;
	private Intent intent;
	private Bundle bundle;
	private Button assignBtn;
	private Button changeassignBtn;
	private ImageView assignIm1, assignIm2, assignVoice;
	private TextView severInformationTv;
	private TextView assignVoiceTime;
	private TextView tasknumTv, houseTv, reporternameTv, reporterphoneTv,
			areaandwhatTv, reporttimeTv, expecttimeTv;
	private EditText problemEdit;
	private Server serverAfter;
	private Server server;
	private TextView titleCenterTv;
	private LinearLayout leftLinLayout;
	private List<Server> servers;
	private String realfunctioncode;
	private String functioncode;
	private String taskstate;
	private String taskcode;
	private String message;
	private String areaname;
	private String areaType;
	private User user;
	private Task task;
	public static int INTENT_FLAG = 0;//
	private boolean canClick = false;
	private ProgressBar loginbar;
	private CustomLoadingDialog uploadingdialog;
	
	private String repairId;
	private String houseId;
	private String houseFullName;
	private LinearLayout servePeopleLv;
	private TextView servernameTv;
	private TextView serverphoneTv;
	private String peopleType;
	private boolean isReporter;
	private String sessionId;
	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case Config.HANDLER_MSG_SUCCESS:
				//根据任务及人员状态判断显示控件
				hideOrShowViews();
				String servername = null , departDispatchername = null , dispatchername = null;
				if (functioncode
						.equals(Config.FUNCTION_REAL_GETREDISPATCHTASKLIST)
						|| functioncode
								.equals(Config.FUNCTION_REAL_OUTTIMEREPAIR)
						|| functioncode
								.equals(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTDISPACHER)) {// 改派、超时派单
					if (null != task.getDepartDispatcher_realName()) {
						departDispatchername = task.getDepartDispatcher_realName();
						servernameTv.setText(task.getDepartDispatcher_realName());
						serverphoneTv.setText(task
								.getDepartDispatcher_mobilePhone());
					}
					if (null != task.getServer_realName() && !task.getServer_realName().equals("")) {
						servername = task.getServer_realName();
						servernameTv.setText(task
								.getServer_realName());
						serverphoneTv.setText(task
								.getServer_mobilePhone());
					}
				} else if (functioncode
						.equals(Config.FUNCTION_REAL_GETMANAGERREDISPATCHTASKLIST)
						|| functioncode
								.equals(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTMANAGER)
						|| functioncode
								.equals(Config.FUNCTION_REAL_OUTTIMEREPAIROFDEPART)) {// 主管改派,超时改派
					if (null != task.getServer_realName()) {
						servername = task.getServer_realName();
						servernameTv.setText(task.getServer_realName());
						serverphoneTv.setText(task.getServer_mobilePhone());
					}
				} else if (functioncode.equals(Config.FUNCTION_REAL_MYAPPLY)) {// 我的提单
					if (peopleType.equals(Config.DEPART_DISPATCHER)) {
						if (null != task.getServer_realName()) {
							servernameTv.setText(task.getServer_realName());
							serverphoneTv.setText(task.getServer_mobilePhone());
						}
					} else {
						if (null != task.getDepartDispatcher_realName()) {
							servernameTv.setText(task
									.getDepartDispatcher_realName());
							serverphoneTv.setText(task
									.getDepartDispatcher_mobilePhone());
						}
					}

				}
				System.out.println("servername--?"+servername);
				System.out.println("dispatchername--?"+dispatchername);
				System.out.println("departDispatchername--?"+departDispatchername);
				tasknumTv.setText(task.getRepairNum());
				houseTv.setText(houseFullName);
				// 维修区域信息拼接
				areaname = Tool.getHouseType(task);
				areaandwhatTv.setText(areaname + "/" + task.getRepairObject());
				if (null != task.getDispatchTime()) {
					if (task.getReportTime().length() > Config.TIMELENGTH) {
						reporttimeTv.setText(task.getReportTime().substring(0,
								Config.TIMELENGTH));
					} else {
						reporttimeTv.setText(task.getReportTime());
					}
				}
				if (null != task.getExpectTime()) {
					if (task.getExpectTime().length() > Config.TIMELENGTH) {
						expecttimeTv.setText(task.getExpectTime().substring(0,
								Config.TIMELENGTH));
					} else {
						expecttimeTv.setText(task.getExpectTime());
					}
				}
				reporternameTv.setText(task.getReporter_realName());
				reporterphoneTv.setText(task.getReporter_phone());
				problemEdit.setText(task.getProblemDescript());
				if (null != task.getProblemImage1()
						&& !task.getProblemImage1().equals("")) {
					assignIm1.setVisibility(View.VISIBLE);
					ImageLoader.getInstance().displayImage(
							"file://" + Config.IMAGE_PATH
									+ task.getProblemImage1(), assignIm1,
							options);
				} else {

					assignIm1.setVisibility(View.INVISIBLE);
				}
				if (null != task.getProblemImage2()
						&& !task.getProblemImage2().equals("")) {
					assignIm2.setVisibility(View.VISIBLE);
					ImageLoader.getInstance().displayImage(
							"file://" + Config.IMAGE_PATH
									+ task.getProblemImage2(), assignIm2,
							options);
				} else {
					assignIm2.setVisibility(View.INVISIBLE);
				}
				if (null != task.getProblemVoice()
						&& !task.getProblemVoice().equals("")) {
					assignVoice.setVisibility(View.VISIBLE);
					assignVoiceTime.setVisibility(View.VISIBLE);
					String voicept = Config.VOICE_PATH+task.getProblemVoice();
					int voicetime = Tool.voiceTime(	AssignAndReassignTaskActivity.this,voicept);
					int realvoicetime = (int) voicetime/1000;
					//assign_repair_voice.setVisibility(View.VISIBLE);
					Log.e("realvoicetime", realvoicetime+"'");
					assignVoiceTime.setText(realvoicetime+"'");
				} else {
					assignVoice.setVisibility(View.INVISIBLE);
					assignVoiceTime.setVisibility(View.INVISIBLE);
				}
				canClick = true;
				loginbar.setVisibility(View.INVISIBLE);
				Toast.makeText(AssignAndReassignTaskActivity.this,
						(String) msg.obj, Toast.LENGTH_SHORT);
				if (!functioncode
						.equals(Config.FUNCTION_REAL_GETPMPROGRESSLIST)) {// 项目经理
					getServers();
				}
				break;
	
			case Config.HANDLER_MSG_POST_SUCCESS:
				Tool.judgedialog(AssignAndReassignTaskActivity.this,
						(String) msg.obj,uploadingdialog, loginbar);
				finish();

				break;
			case Config.HANDLER_MSG_GETSEVER_SUCCESS:
				loginbar.setVisibility(View.INVISIBLE);
				System.out.println("servers.size()+" + servers.size());
				
				if (taskstate.contains(Config.TASKSTATE_NOTDISTRIBUTE)) {//待分配
					for (Server s : servers) {
						if (s.isSelected()) {
							server = s;
						}
					}
				} else {
					for (Server s : servers) {
						Log.e("选择人员", "s>>>"+s.getUserId());
						Log.e("选择人员", "getDepartDispatcher_id>>>"+task.getDepartDispatcher_id());
						Log.e("选择人员", "getServer_id>>>"+task.getServer_id());
						if (null != task.getDepartDispatcher_id() && task.getDepartDispatcher_id().equals(
								s.getUserId())) {
							server = s;
							serverAfter = server;
						}else if(null != task.getServer_id() && task.getServer_id().equals(
										s.getUserId())) {
							server = s;
							serverAfter = server;
						}
					}
				}
				break;
			case Config.HANDLER_MSG_FAIL:
				if (uploadingdialog != null) {
					Tool.judgedialog(AssignAndReassignTaskActivity.this,
							(String) msg.obj,uploadingdialog, loginbar);
				}
				loginbar.setVisibility(View.INVISIBLE);
				Toast.makeText(AssignAndReassignTaskActivity.this,
						(String) msg.obj, Toast.LENGTH_SHORT).show();
				break;
			case Config.HANDLER_MSG_GETTASK_FAIL:
				if (uploadingdialog != null) {
					if (uploadingdialog.isShowing()) {
						uploadingdialog.dismiss();
					}
				}
				loginbar.setVisibility(android.view.View.INVISIBLE);
				new AlertDialog.Builder(AssignAndReassignTaskActivity.this)
						.setTitle("提醒")
						.setMessage((String) msg.obj)
						.setPositiveButton(
								"取消",
								new android.content.DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface arg0,
											int arg1) {
										// TODO Auto-generated method stub
										
										finish();
									}
								}).create().show();
				break;
			case Config.HANDLER_MSG_REPAIR_REDISPATCH_SUCCESS:
				Tool.judgedialog(AssignAndReassignTaskActivity.this,
						(String) msg.obj,uploadingdialog, loginbar);
				DataSupport.deleteAll(Task.class, "repairId = ?", repairId);
				//Log.e("申请改派删除任务", task_id + "删除成功");
				finish();
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};


	public static final DisplayImageOptions options = new DisplayImageOptions.Builder()
			.cacheInMemory(false) // 设置下载的图片是否缓存在内存中
			.cacheOnDisk(false).bitmapConfig(Bitmap.Config.RGB_565) // 设置下载的图片是否缓存在SD卡中
			.displayer(new RoundedBitmapDisplayer(10)) // 设置成圆角图片
			.build();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_assign_task);
		initData();
		initViews();
		initEvents();
		loginbar.setVisibility(View.VISIBLE);
		new Thread(getDataRun).start();
		/*
		 * if(INTENT_FLAG == 0){ new Thread(getDataRun).start(); }
		 */
	}
	
	private void initData(){
		intent = getIntent();
		bundle = intent.getExtras();
		functioncode = bundle.getString(Config.FUNCTIONCODE);
		
		Log.e("functioncode-->1", "---->"+functioncode);
		repairId = bundle.getString(Config.REPAIRID);
		houseId = bundle.getString(Config.HOUSEID);
		areaType = bundle.getString(Config.AREATYPE);
		taskstate = bundle.getString(Config.TASKSTATE);
		taskcode = bundle.getString(Config.STATUS_TYPE_CODE);
		repairId = bundle.getString(Config.REPAIRID);
		houseFullName = bundle.getString(Config.HOUSEFULLNAME);
		peopleType = bundle.getString(Config.PEOPLETYPE);
		isReporter = bundle.getBoolean(Config.ISREPORTER);
		user = SingleSample.getInstance(this).getUser();
		if (null != user) {
			if (null != user.getSessionId()
					&& !user.getSessionId().equals("")) {
				sessionId = user.getSessionId();
			}
		}
	}

	@Override
	protected void initViews() {
		// TODO Auto-generated method stub
		titleCenterTv = (TextView) findViewById(R.id.titlebar_left_center_title);
		leftLinLayout = (LinearLayout) findViewById(R.id.titlebar_left_left_layout);
		titleCenterTv.setText("任务详情");
		loginbar = (ProgressBar) findViewById(R.id.assign_progressBar);
		// selectServerRv = (RelativeLayout)
		// findViewById(R.id.rv_select_servicepeople);
		servePeopleLv = (LinearLayout) findViewById(R.id.tx_serve_people);
		tasknumTv = (TextView) findViewById(R.id.assign_tasknum);
		houseTv = (TextView) findViewById(R.id.assign_hosue);
		reporternameTv = (TextView) findViewById(R.id.assign_reporter);
		reporterphoneTv = (TextView) findViewById(R.id.assign_reporterphone);
		servernameTv = (TextView) findViewById(R.id.assign_server);
		serverphoneTv = (TextView) findViewById(R.id.assign_serverphone);
		areaandwhatTv = (TextView) findViewById(R.id.assign_areaandwhat);
		reporttimeTv = (TextView) findViewById(R.id.assign_reporttime);
		expecttimeTv = (TextView) findViewById(R.id.assign_expecttime);
		problemEdit = (EditText) findViewById(R.id.assign_problemedit);
		assignBtn = (Button) findViewById(R.id.btn_assign);
		assignIm1 = (ImageView) findViewById(R.id.assign_image1);
		assignIm2 = (ImageView) findViewById(R.id.assign_image2);
		assignVoice = (ImageView) findViewById(R.id.assign_voice);
		assignVoiceTime = (TextView) findViewById(R.id.assign_recordtime);
		// severInformationTv = (TextView)
		// findViewById(R.id.tv_server_information);
		changeassignBtn = (Button) findViewById(R.id.btn_changeassign);
		assignIm1.setVisibility(View.INVISIBLE);
		assignIm2.setVisibility(View.INVISIBLE);
		assignVoice.setVisibility(View.INVISIBLE);
		assignVoiceTime.setVisibility(View.INVISIBLE);
		// 电话
		reporterphoneTv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
		serverphoneTv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);

		reporterphoneTv.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				// TODO Auto-generated method stub
				intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"
						+ reporterphoneTv.getText().toString()));
				startActivity(intent);
			}
		});
		serverphoneTv.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				// TODO Auto-generated method stub
				intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"
						+ serverphoneTv.getText().toString()));
				startActivity(intent);
			}
		});
		
		//根据任务及人员状态判断显示控件
		hideOrShowViews();
		

	}

	@Override
	protected void initEvents() {
		// TODO Auto-generated method stub
		leftLinLayout.setOnClickListener(this);
		// selectServerRv.setOnClickListener(this);
		assignBtn.setOnClickListener(this);
		assignIm1.setOnClickListener(this);
		assignIm2.setOnClickListener(this);
		assignVoice.setOnClickListener(this);
		changeassignBtn.setOnClickListener(this);
		SysApplication.getInstance().addActivity(this);

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Bundle b = new Bundle();
		switch (v.getId()) {
	
		case R.id.titlebar_left_left_layout:
			finish();
			break;
		case R.id.assign_image1:
			Intent intent = new Intent(AssignAndReassignTaskActivity.this,
					ViewPagerActivity.class);
			intent.putExtra("image1",
					"file://" + Config.IMAGE_PATH + task.getProblemImage1());
			if (!task.getProblemImage2().equals("")) {
				intent.putExtra("image2",
						"file://" + Config.IMAGE_PATH + task.getProblemImage2());
			}
			startActivity(intent);
			break;
		case R.id.assign_image2:
			Intent intent1 = new Intent(AssignAndReassignTaskActivity.this,
					ViewPagerActivity.class);
			intent1.putExtra("image1",
					"file://" + Config.IMAGE_PATH + task.getProblemImage2());
			intent1.putExtra("image2",
					"file://" + Config.IMAGE_PATH + task.getProblemImage1());
			startActivity(intent1);
			break;
		case R.id.assign_voice:
			File clickfile = new File(Config.VOICE_PATH
					+ task.getProblemVoice());
			Intent it = new Intent();
			it.setAction(Intent.ACTION_VIEW);

			it.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			it.putExtra("oneshot", 0);
			it.putExtra("configchange", 0);
			it.setDataAndType(Uri.parse("file:" + clickfile.getPath()),
					"audio/*");
			startActivity(it);
			break;
		case R.id.btn_assign:
		
			if (canClick) {
				if (null != serverAfter) {
					b.putSerializable(Config.SERVERAFTER, serverAfter);
				}
				
				if (functioncode.equals(Config.FUNCTION_REAL_MYAPPLY)) {// 我的提单

					if (peopleType.equals(Config.DEPART_DISPATCHER)) {
						if (taskstate.contains(Config.TASKSTATE_NOTDISTRIBUTE)) {//待分配
							b.putString(Config.FUNCTIONCODE,
									Config.FUNCTION_REAL_GETMANAGERDISPATCHTASKLIST);
						} else {
							b.putString(Config.FUNCTIONCODE,
									Config.FUNCTION_REAL_GETMANAGERREDISPATCHTASKLIST);
						}
					} else {
						if (taskstate.contains(Config.TASKSTATE_NOTDISTRIBUTE)||taskstate.contains(Config.TASKSTATE_GETTASK)) {//待分配
							b.putString(Config.FUNCTIONCODE,
									Config.FUNCTION_REAL_GETDISPATCHTASKLIST);
						} else {
							b.putString(Config.FUNCTIONCODE,
									Config.FUNCTION_REAL_GETREDISPATCHTASKLIST);
						}
					}

				} else if (functioncode
						.equals(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTMANAGER)) {
					if (taskstate.contains(Config.TASKSTATE_NOTDISTRIBUTE)) {//待分配
						b.putString(Config.FUNCTIONCODE,
								Config.FUNCTION_REAL_GETMANAGERDISPATCHTASKLIST);
					} else {
						b.putString(Config.FUNCTIONCODE,
								Config.FUNCTION_REAL_GETMANAGERREDISPATCHTASKLIST);
					}
				} else if (functioncode
						.equals(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTDISPACHER)) {
					if (taskstate.contains(Config.TASKSTATE_NOTDISTRIBUTE)) {//待分配
						b.putString(Config.FUNCTIONCODE,
								Config.FUNCTION_REAL_GETDISPATCHTASKLIST);
					} else {
						b.putString(Config.FUNCTIONCODE,
								Config.FUNCTION_REAL_GETREDISPATCHTASKLIST);
					}
				} else {
					b.putString(Config.FUNCTIONCODE, functioncode);
				}
				b.putString(Config.REPAIRID, repairId);
				b.putString(Config.HOUSEID, task.getHouse_id());
				b.putString(Config.PEOPLETYPE, peopleType);
				b.putString(Config.TASKSTATE, taskstate);
				b.putSerializable(Config.SERVERLIST,(Serializable) servers);
				intent = new Intent(AssignAndReassignTaskActivity.this,
						SelectServerActivity.class);
				intent.putExtras(b);
				startActivityForResult(intent, 0);
				finish();
			} else {
				showShortToast("请稍后，数据未加载完成。。。");
			}
			break;
		case R.id.btn_changeassign:
			Toast.makeText(AssignAndReassignTaskActivity.this, "点击申请改派",
					Toast.LENGTH_SHORT).show();
			// 标准的对话框封装
			final CustomDialog dialog2 = new CustomDialog(
					AssignAndReassignTaskActivity.this);

			dialog2.setTitle("申请改派");
			dialog2.setDetial("是否要申请改派？");
			dialog2.setLeftOnClick(new OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog2.dismiss();
				}
			});
			dialog2.show();
			dialog2.setRightOnClick(new OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog2.dismiss();
					uploadingdialog = new CustomLoadingDialog(
							AssignAndReassignTaskActivity.this, "申请改派...");
					if (uploadingdialog.isShowing()) {
						uploadingdialog.dismiss();
					} else {
						uploadingdialog.show();
					}
					new Thread(postRedispatchRun).start();
				}
			});
			dialog2.show();

			break;
		}
	}

	Runnable getDataRun = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			getData();
		}
	};

	// 定义发送请求的方法
	private void getData() {
		if (Tool.isNetworkAvailable(AssignAndReassignTaskActivity.this)) {
			try {
				String result = null;
				Log.e("AssignAndReassignTaskActivity>>realfunctioncode",
						Config.FUNCTION_REAL_GETREPAIRPROGRESSDETAIL);
				Log.e("AssignAndReassignTaskActivity>>houseId",
						houseId);
				String url = Config.SERVER_URL
						+ user.getFunctionlistFromUser(Config.FUNCTION_REAL_GETREPAIRPROGRESSDETAIL).get(0)
								.getFunctionUrl();
				Map<String, String> map = new HashMap<String, String>();
				map.put("functionCode", Config.FUNCTION_REAL_GETREPAIRPROGRESSDETAIL);
				map.put("repairId", repairId);
				map.put("houseId", houseId);
				String setsessionid = "";
				User user = SingleSample.getInstance(
						AssignAndReassignTaskActivity.this).getUser();
				if (null != user) {
					if (null != user.getSessionId()
							&& !user.getSessionId().equals("")) {
						setsessionid = user.getSessionId();
					}
				}
				result = HttpUtil.postRequestSe(url, map, setsessionid);
				Log.e("任务详情的result", result);
				result = result.replace("rows", "tasks");
				String total = new JSONObject(result).getString("total");
				String message = new JSONObject(result).getString("message");
				String flag = new JSONObject(result).getString("flag");
				String rows = new JSONObject(result).getString("tasks");
				if (total.equals("0")) {
					mHandler.obtainMessage(Config.HANDLER_MSG_GETTASK_FAIL,
							"该任务不存在！").sendToTarget();
				} else {
					java.lang.reflect.Type type = new TypeToken<Task>() {
					}.getType();
					Gson gson = new Gson();
					JSONArray jsonArray = new JSONArray(rows);
					JSONObject jsonObject = jsonArray.getJSONObject(0);
					task = gson.fromJson(jsonObject.toString(), type);
					task = Tool.setTaskAll(functioncode, peopleType,
							task, user);
					if (flag.equals(Config.CONNECT_SUCCESS2)) {

						boolean flagb = false;

						String urlstr = Config.SERVER_URL
								+ user.getFunctionlistFromUser(
										Config.FUNCTION_REAL_DOWNLOADREPAIRFILE)
										.get(0).getFunctionUrl();
						
						map.put("sessionId", sessionId);
						map.put("functionCode",
								Config.FUNCTION_REAL_DOWNLOADREPAIRFILE);
						if (null != task.getProblemImage1()
								&& !task.getProblemImage1().equals("")) {
							map.put("fileName", task.getProblemImage1());
							flagb = UploadService.downFile(urlstr,
									Config.IMAGE_PATH, map);
						}
						if (null != task.getProblemImage2()
								&& !task.getProblemImage2().equals("")) {
							map.put("fileName", task.getProblemImage2());
							flagb = UploadService.downFile(urlstr,
									Config.IMAGE_PATH, map);
						}
						if (null != task.getProblemVoice()
								&& !task.getProblemVoice().equals("")) {
							map.put("fileName", task.getProblemVoice());
							flagb = UploadService.downFile(urlstr,
									Config.VOICE_PATH, map);
						}
						if (flagb) {
							mHandler.obtainMessage(Config.HANDLER_MSG_SUCCESS,
									message).sendToTarget();// 通知主线程数据发送成功
						} else {
							mHandler.obtainMessage(Config.HANDLER_MSG_SUCCESS,
									message).sendToTarget();// 通知主线程数据发送成功
						}
					} else {
						mHandler.obtainMessage(Config.HANDLER_MSG_FAIL, message)
								.sendToTarget();// 通知主线程数据发送成功
					}
				}

			} catch (Exception e) {
				Log.e("ServiceScheduleActivity", "json数据获取报错");
				mHandler.obtainMessage(Config.HANDLER_MSG_FAIL, "json解析出错")
						.sendToTarget();
				e.printStackTrace();
			}

		} else {
			mHandler.obtainMessage(Config.HANDLER_MSG_FAIL, "请设置网络")
					.sendToTarget();

		}
	}

	// 请求服务人员列表
	private void getServers() {
		if (Tool.isNetworkAvailable(AssignAndReassignTaskActivity.this)) {
			try {

				User u;
				String result = null;
				String url = null;
				Map<String, String> map = new HashMap<String, String>();
				//System.out.println("houseId--------->" + task.getHouse_id());
				System.out.println("houseId--------->" + houseId);
				if (functioncode
						.equals(Config.FUNCTION_REAL_GETDISPATCHTASKLIST)
						|| functioncode
								.equals(Config.FUNCTION_REAL_GETREDISPATCHTASKLIST)
						|| functioncode
								.equals(Config.FUNCTION_REAL_OUTTIMEREPAIR)
						|| functioncode
								.equals(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTDISPACHER)) {// 改派、超时派单
					map.put("functionCode", Config.FUNCTION_REAL_GETMANAGERLIST);
					
					url = Config.SERVER_URL
							+ user.getFunctionlistFromUser(
									Config.FUNCTION_REAL_GETMANAGERLIST).get(0)
									.getFunctionUrl();
					/*System.out.println("houseId---------改派>"
							+ task.getHouse_id());*/
					System.out.println("houseId---------改派>" + houseId);
				} else if (functioncode
						.equals(Config.FUNCTION_REAL_GETMANAGERDISPATCHTASKLIST)
						|| functioncode
								.equals(Config.FUNCTION_REAL_GETMANAGERREDISPATCHTASKLIST)
						|| functioncode
								.equals(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTMANAGER)
						|| functioncode
								.equals(Config.FUNCTION_REAL_OUTTIMEREPAIROFDEPART)) {// 部门主管派单、部门主管改派，超时改派
					map.put("functionCode", Config.FUNCTION_REAL_GETSERVERLIST);
					//map.put("functionCode", Config.FUNCTION_REAL_GETMANAGERLIST);
					map.put("departDispatcherId", user.getUserId());
					url = Config.SERVER_URL
							+ user.getFunctionlistFromUser(
									Config.FUNCTION_REAL_GETSERVERLIST).get(0)
									.getFunctionUrl();
				
					System.out.println("managerId---------部门主管派单、改派>"
							+ user.getUserId());
				} else if (functioncode.equals(Config.FUNCTION_REAL_MYAPPLY)) {
					if (peopleType.equals(Config.DEPART_DISPATCHER)) {//部门派单员
						map.put("functionCode",
								Config.FUNCTION_REAL_GETSERVERLIST);
						map.put("departDispatcherId", user.getUserId());
						
						url = Config.SERVER_URL
								+ user.getFunctionlistFromUser(
										Config.FUNCTION_REAL_GETSERVERLIST)
										.get(0).getFunctionUrl();
					} else {
						map.put("functionCode",
								Config.FUNCTION_REAL_GETMANAGERLIST);
						
						url = Config.SERVER_URL
								+ user.getFunctionlistFromUser(
										Config.FUNCTION_REAL_GETMANAGERLIST)
										.get(0).getFunctionUrl();
					}
				}
				//map.put("houseId", task.getHouse_id());
				map.put("houseId", houseId);
				String setsessionid = "";
				User user = SingleSample.getInstance(
						AssignAndReassignTaskActivity.this).getUser();
				if (null != user) {
					if (null != user.getSessionId()
							&& !user.getSessionId().equals("")) {
						setsessionid = user.getSessionId();
					}
				}
				result = HttpUtil.postRequestSe(url, map, setsessionid);
				Log.e("获取服务人员的result", result);
				if (result.contains("rows")) {
					result = result.replace("rows", "servers");
				}
				if (result.contains("departDispatcherList")) {
					result = result.replace("departDispatcherList", "servers");
				}
				message = new JSONObject(result).getString("message");
				String flag = new JSONObject(result).getString("flag");
				if(flag.equals(Config.CONNECT_SUCCESS2)){
					java.lang.reflect.Type type = new TypeToken<User>() {
					}.getType();
					Gson gson = new Gson();
					DataSupport.deleteAll(Server.class);
					u = gson.fromJson(result, type);
					servers = u.getServers();
					mHandler.obtainMessage(Config.HANDLER_MSG_GETSEVER_SUCCESS,
							message).sendToTarget();// 通知主线程数据发送成功
				}else{
					mHandler.obtainMessage(Config.HANDLER_MSG_GETSEVER_SUCCESS,
							message).sendToTarget();// 通知主线程数据发送成功
				}
			
				
			} catch (Exception e) {
				Log.e("ServiceScheduleActivity", "json数据获取报错");
				mHandler.obtainMessage(Config.HANDLER_MSG_FAIL, "json数据获取报错")
						.sendToTarget();
				e.printStackTrace();
			}

		} else {
			mHandler.obtainMessage(Config.HANDLER_MSG_FAIL, "请设置网络")
					.sendToTarget();

		}
	}

	Runnable postDistributeRun = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			postDistribute();
		}
	};

	// 定义发送请求的方法
	private void postDistribute() {
		if (Tool.isNetworkAvailable(AssignAndReassignTaskActivity.this)) {
			try {
				String result = null;
				String url = null;
				Map<String, String> map = new HashMap<String, String>();
				if (functioncode
						.equals(Config.FUNCTION_REAL_GETDISPATCHTASKLIST)) {// 报修分配
					url = Config.SERVER_URL
							+ user.getFunctionlistFromUser(
									Config.FUNCTION_REAL_REPAIRDISPATCHCOMPLETE)
									.get(0).getFunctionUrl();
					map.put("functionCode",
							Config.FUNCTION_REAL_REPAIRDISPATCHCOMPLETE);

				} else if (functioncode
						.equals(Config.FUNCTION_REAL_GETREDISPATCHTASKLIST)
						|| functioncode
								.equals(Config.FUNCTION_REAL_OUTTIMEREPAIR)
						|| functioncode
								.equals(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTDISPACHER)) {// 改派、超时派单
					url = Config.SERVER_URL
							+ user.getFunctionlistFromUser(
									Config.FUNCTION_REAL_REPAIRREDISPATCHCOMPLETE)
									.get(0).getFunctionUrl();
					map.put("functionCode",
							Config.FUNCTION_REAL_REPAIRREDISPATCHCOMPLETE);
				} else if (functioncode
						.equals(Config.FUNCTION_REAL_GETMANAGERDISPATCHTASKLIST)) {// 部门主管派单
					url = Config.SERVER_URL
							+ user.getFunctionlistFromUser(
									Config.FUNCTION_REAL_MANAGERDISPATCHCOMPLETE)
									.get(0).getFunctionUrl();
					map.put("functionCode",
							Config.FUNCTION_REAL_MANAGERDISPATCHCOMPLETE);
				} else if (functioncode
						.equals(Config.FUNCTION_REAL_GETMANAGERREDISPATCHTASKLIST)
						|| functioncode
								.equals(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTMANAGER)
						|| functioncode
								.equals(Config.FUNCTION_REAL_OUTTIMEREPAIROFDEPART)) {// 部门主管改派，超时改派
					url = Config.SERVER_URL
							+ user.getFunctionlistFromUser(
									Config.FUNCTION_REAL_MANAGERREDISPATCHCOMPLETE)
									.get(0).getFunctionUrl();
					map.put("functionCode",
							Config.FUNCTION_REAL_MANAGERREDISPATCHCOMPLETE);
				}
				map.put("repairId", task.getRepairId());
				map.put("serverId", serverAfter.getUserId());
				if (server != null) {
					map.put("orignalServerId", server.getUserId());
				}

				map.put("houseId", task.getHouse_id());
				String setsessionid = "";
				User user = SingleSample.getInstance(
						AssignAndReassignTaskActivity.this).getUser();
				if (null != user) {
					if (null != user.getSessionId()
							&& !user.getSessionId().equals("")) {
						setsessionid = user.getSessionId();
					}
				}
				result = HttpUtil.postRequestSe(url, map, setsessionid);
				Log.e("完成派单的result", result);
				result = result.replace("rows", "tasks");
				message = new JSONObject(result).getString("message");
				String flag = new JSONObject(result).getString("flag");
				if (flag.equals(Config.CONNECT_SUCCESS2)) {
					mHandler.obtainMessage(Config.HANDLER_MSG_POST_SUCCESS,
							message).sendToTarget();// 通知主线程数据发送成功
				} else {
					mHandler.obtainMessage(Config.HANDLER_MSG_FAIL, message)
							.sendToTarget();// 通知主线程数据发送成功
				}
			} catch (Exception e) {
				Log.e("ServiceScheduleActivity", "json数据获取报错");
				message = "json数据获取报错";
				mHandler.obtainMessage(Config.HANDLER_MSG_FAIL, message)
						.sendToTarget();
				e.printStackTrace();
			}

		} else {
			message = "请设置网络";
			mHandler.obtainMessage(Config.HANDLER_MSG_FAIL, message)
					.sendToTarget();

		}
	}

	// 申请改派线程
	Runnable postRedispatchRun = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			postRedispatch();
		}
	};

	// 申请改派
	private void postRedispatch() {
		if (Tool.isNetworkAvailable(AssignAndReassignTaskActivity.this)) {
			try {
				String result = null;
				Map<String, String> map = new HashMap<String, String>();
				String functionCodeStr = "";
				
				String url = Config.SERVER_URL
						+ user.getFunctionlistFromUser(
								Config.FUNCTION_REAL_MANAGERREDISPATCHAPPLY)
								.get(0).getFunctionUrl();
			
				if (task.getStatusType_typeCode().equals(
						Config.TYPECODE_MANAGERDISPATCH)) {
					functionCodeStr = Config.TYPECODE_MANAGERAROMD;
				} else if (task.getStatusType_typeCode().equals(
						Config.TYPECODE_RECEIVEORDER)
						|| task.getStatusType_typeCode().equals(
								Config.TYPECODE_SERVERAROG)) {
					functionCodeStr = Config.TYPECODE_MANAGERPROG;
				} else if (task.getStatusType_typeCode().equals(
						Config.TYPECODE_SERVE)
						|| task.getStatusType_typeCode().equals(
								Config.TYPECODE_REMINDE)
						|| task.getStatusType_typeCode().equals(
								Config.TYPECODE_SERVERAROS)) {
					functionCodeStr = Config.TYPECODE_MANAGERAROS;
				}
				Log.e("申请改派functionCode", functionCodeStr);
				map.put("functionCode", functionCodeStr);
				map.put("repairId", task.getRepairId());
				String setsessionid = "";
				user = SingleSample.getInstance(
						AssignAndReassignTaskActivity.this).getUser();
				if (null != user) {
					if (null != user.getSessionId()
							&& !user.getSessionId().equals("")) {
						setsessionid = user.getSessionId();
					}
				}
				result = HttpUtil.postRequestSe(url, map, setsessionid);
				Log.e("主管申请改派的result", result);
				String message = new JSONObject(result).getString("message");
				String flag = new JSONObject(result).getString("flag");
				if (flag.equals(Config.CONNECT_SUCCESS2)) {
					mHandler.obtainMessage(
							Config.HANDLER_MSG_REPAIR_REDISPATCH_SUCCESS,
							message).sendToTarget();// 通知主线程数据发送成功

				} else {
					mHandler.obtainMessage(Config.HANDLER_MSG_FAIL, message)
							.sendToTarget();

				}

			} catch (Exception e) {
				mHandler.obtainMessage(Config.HANDLER_MSG_FAIL, "json数据获取出错")
						.sendToTarget();

				e.printStackTrace();
			}

		} else {
			mHandler.obtainMessage(Config.HANDLER_MSG_FAIL, "请设置网络")
					.sendToTarget();
		}
	}

	private void hideOrShowViews(){
		if (functioncode.equals(Config.FUNCTION_REAL_GETDISPATCHTASKLIST)) {// 报修分配
			realfunctioncode = Config.FUNCTION_REAL_GETDISPATCHTASKDETAIL;
			changeassignBtn.setVisibility(View.GONE);
			assignBtn.setText("派单");
		} else if (functioncode
				.equals(Config.FUNCTION_REAL_GETREDISPATCHTASKLIST)) {// 改派
			realfunctioncode = Config.FUNCTION_REAL_GETREDISPATCHTASKDETAIL;
			changeassignBtn.setVisibility(View.GONE);
			servePeopleLv.setVisibility(View.VISIBLE);
			assignBtn.setText("改派");
		} else if (functioncode.equals(Config.FUNCTION_REAL_OUTTIMEREPAIR)) {// 超时派单（派单员）
			realfunctioncode = Config.FUNCTION_REAL_GETREDISPATCHTASKDETAIL;
			changeassignBtn.setVisibility(View.GONE);
			servePeopleLv.setVisibility(View.VISIBLE);
			assignBtn.setText("超时改派");

		} else if (functioncode.equals(Config.FUNCTION_REAL_OUTTIMEREPAIROFDEPART)) {// 超时派单（部门派单员）
			realfunctioncode = Config.FUNCTION_REAL_GETDEPARTDISPARCHREDISPATCHTASKDETAIL;
			changeassignBtn.setVisibility(View.GONE);
			servePeopleLv.setVisibility(View.VISIBLE);
			assignBtn.setText("超时改派");

		}else if (functioncode
				.equals(Config.FUNCTION_REAL_GETMANAGERDISPATCHTASKLIST)) {// 主管派单
			realfunctioncode = Config.FUNCTION_REAL_GETMANAGERDISPATCHTASKDETAIL;
			changeassignBtn.setVisibility(View.VISIBLE);
			assignBtn.setText("派单");
		} else if (functioncode
				.equals(Config.FUNCTION_REAL_GETMANAGERREDISPATCHTASKLIST)) {// 主管改派
			realfunctioncode = Config.FUNCTION_REAL_MANAGERREDISPATCHTASKDETAIL;
			changeassignBtn.setVisibility(View.VISIBLE);
			servePeopleLv.setVisibility(View.VISIBLE);
			assignBtn.setText("改派");
		} else if (functioncode
				.equals(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTMANAGER) // 主管进度列表
				||(functioncode.equals(Config.FUNCTION_REAL_MYAPPLY) && isReporter)){// 我的提单
			if (taskstate.contains("待分配")) {
				realfunctioncode = Config.FUNCTION_REAL_GETREPAIRPROGRESSDETAIL;
				changeassignBtn.setVisibility(View.VISIBLE);
				servePeopleLv.setVisibility(View.GONE);
				assignBtn.setText("派单");
			} else {
				realfunctioncode = Config.FUNCTION_REAL_GETREPAIRPROGRESSDETAIL;
				changeassignBtn.setVisibility(View.VISIBLE);
				servePeopleLv.setVisibility(View.VISIBLE);
				assignBtn.setText("改派");
			}
		} else if (functioncode
				.equals(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTDISPACHER)) {// 派单员进度列表
			if (taskstate.contains("待分配")) {
				realfunctioncode = Config.FUNCTION_REAL_GETREPAIRPROGRESSDETAIL;
				changeassignBtn.setVisibility(View.GONE);
				servePeopleLv.setVisibility(View.GONE);
				assignBtn.setText("派单");
			} else {
				realfunctioncode = Config.FUNCTION_REAL_GETREPAIRPROGRESSDETAIL;
				changeassignBtn.setVisibility(View.GONE);
//一级派单员显示；二级派单员（二级申请改派时，服务人员改为二级派单员的名字）
				servePeopleLv.setVisibility(View.VISIBLE);
				/*if(null != task.getDepartDispatcher_realName()){
					servePeopleLv.setVisibility(View.GONE);
				} else{
					servePeopleLv.setVisibility(View.VISIBLE);   
				}*/
				assignBtn.setText("改派");
			}
		} else if (functioncode.equals(Config.FUNCTION_REAL_GETPMPROGRESSLIST)) {// 项目经理
			realfunctioncode = Config.FUNCTION_REAL_GETREPAIRPROGRESSDETAIL;
			changeassignBtn.setVisibility(View.GONE);
			assignBtn.setVisibility(View.GONE);
			selectServerRv.setVisibility(View.GONE);
		} else if (functioncode.equals(Config.FUNCTION_REAL_MYAPPLY)){// 我的提单
			if (peopleType.equals(Config.DEPART_DISPATCHER)) {
				if (taskstate.contains("待分配")) {
					realfunctioncode = Config.FUNCTION_REAL_GETREPAIRPROGRESSDETAIL;
					changeassignBtn.setVisibility(View.GONE);
					servePeopleLv.setVisibility(View.GONE);
					assignBtn.setVisibility(View.GONE);
					//assignBtn.setText("派单");
				} else {
					realfunctioncode = Config.FUNCTION_REAL_GETREPAIRPROGRESSDETAIL;
					changeassignBtn.setVisibility(View.VISIBLE);
					servePeopleLv.setVisibility(View.VISIBLE);
					assignBtn.setText("改派");
				}
			} else {
				if (taskstate.contains("待分配")||taskstate.contains("受理")) {
					realfunctioncode = Config.FUNCTION_REAL_GETREPAIRPROGRESSDETAIL;
					changeassignBtn.setVisibility(View.GONE);
					servePeopleLv.setVisibility(View.GONE);
					assignBtn.setText("派单");
				} else {
					realfunctioncode = Config.FUNCTION_REAL_GETREPAIRPROGRESSDETAIL;
					changeassignBtn.setVisibility(View.GONE);
					servePeopleLv.setVisibility(View.VISIBLE);
					assignBtn.setText("改派");
				}
			}

		}
	}
	
	// 回调方法，从第二个页面回来的时候会执行这个方法
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (data != null) {
			if (data.getExtras() != null) {
				serverAfter = (Server) data.getExtras().getSerializable(
						Config.SERVERAFTER);
			}
		}
		// 根据上面发送过去的请求吗来区别
		switch (requestCode) {
		case 0:
			if (serverAfter != null) {
				severInformationTv.setText(serverAfter.getRealName() + " "
						+ serverAfter.getMobilePhone());
			}
			break;

		default:
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}
